package com.nf.health.app.datamain.activity;

import android.app.TimePickerDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.TimePicker;

import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.ViewUtil;

import cn.bluetools.BluetoothLeService;
import cn.bluetools.Pedometer_TypeInfo.Pedometer_Type;

public class BraceletSleepActivity extends BaseActivity {

	protected static final String TAG = BraceletSleepActivity.class.getSimpleName();
	private TextView tv_start_time;
	private TextView tv_end_time;
	private String startTime;
	private String endTime;
	private String[] times;
	private View rl_start_time;
	private View rl_end_time;
	private ServiceConnection mServiceConnection;
	private BluetoothLeService mBluetoothLeService; // 蓝牙服务类
	private LocalBroadcastManager localBroadcastManager;
	/**
	 * 接收蓝牙服务传入的事件消息，或者是接收到的蓝牙数据
	 */
	private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
				String[] startTimeArray = startTime.split(":");
				String[] endTimeArray = endTime.split(":");
				mBluetoothLeService.setAutoSleepRange(PreferenceHelper.getBoolean("isAutoSleep", false),  Integer.parseInt(startTimeArray[0]), Integer.parseInt(startTimeArray[1]), Integer.parseInt(endTimeArray[0]), Integer.parseInt(endTimeArray[1]));
			} else if (BluetoothLeService.ACTION_GATT_SERVICES_TIMEOUT
					.equals(action)) {
				// 蓝牙通讯超时，这里可以重发未响应的命令
				hideLoading();
			}

			else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
				// 蓝牙断开
				hideLoading();
			} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
				// 接收到蓝牙数据
				hideLoading();
			}

		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitleBar(R.layout.layout_common_header);
		
		setContent(R.layout.activity_bracelet_sleep);
		
		ViewUtil.setText(this, R.id.titlebar_title_tv, "预设睡眠");
		
		initView();
		
		initBlueTooth();
	}
	
	private void initBlueTooth() {
		localBroadcastManager = LocalBroadcastManager.getInstance(this);
		
		mServiceConnection = new ServiceConnection() {
			@Override
			public void onServiceConnected(ComponentName componentName,
					IBinder service) {
				mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
				// BluetoothLeService.setPedometerType(Pedometer_TypeInfo.Pedometer_Type.L28S);
				BluetoothLeService.setPedometerType(Pedometer_Type.L28T);
			}

			@Override
			public void onServiceDisconnected(ComponentName componentName) {
				mBluetoothLeService = null;
			}
		};

		Intent bleService = new Intent(this, BluetoothLeService.class);
		bindService(bleService, mServiceConnection, Context.BIND_AUTO_CREATE);
		localBroadcastManager.registerReceiver(mGattUpdateReceiver, BluetoothLeService.makeGattUpdateIntentFilter());		
	}

	private void initView() {
		startTime = PreferenceHelper.getString("startTime", "23:00");
		endTime = PreferenceHelper.getString("endTime", "7:00");
		
		
		rl_start_time = ViewUtil.getView(this, R.id.rl_start_time);
		rl_end_time = ViewUtil.getView(this, R.id.rl_end_time);
		tv_start_time = ViewUtil.getView(this, R.id.tv_start_time);
		tv_end_time = ViewUtil.getView(this, R.id.tv_end_time);
		tv_start_time.setText(startTime);
		tv_end_time.setText(endTime);
		
		
		TextView titlebar_right_tv = ViewUtil.getView(this, R.id.titlebar_right_tv);
		titlebar_right_tv.setOnClickListener(this);
		titlebar_right_tv.setText("保存");
		titlebar_right_tv.setVisibility(View.VISIBLE);
		
		boolean isAutoSleep = PreferenceHelper.getBoolean("isAutoSleep", false);
		
		final CheckBox cb_auto_sleep = ViewUtil.getView(this, R.id.cb_auto_sleep);
		cb_auto_sleep.setChecked(isAutoSleep);
		setListener(isAutoSleep);
		cb_auto_sleep.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				cb_auto_sleep.setChecked(isChecked);
				setListener(isChecked);
				PreferenceHelper.putBoolean("isAutoSleep", isChecked);
			}
		});		
	}

	private void setListener(boolean isAutoSleep) {
		if(isAutoSleep){
			rl_start_time.setOnClickListener(this);
			rl_end_time.setOnClickListener(this);
		}else {
			rl_start_time.setOnClickListener(null);
			rl_end_time.setOnClickListener(null);
		}		
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		super.onClick(v);
		switch (v.getId()) {
		case R.id.titlebar_right_tv:
			if(PreferenceHelper.getBoolean("isAutoSleep", false)){
				showLoading("设置中...");
				mBluetoothLeService.connect(PreferenceHelper.getString(PreferenceHelper.BLUETOOTH_DEVICE_ADDRESS, ""), "");
			}else{
				
			}
			break;
		case R.id.rl_start_time:
			times = startTime.split(":");
			initTimePicker(false, Integer.parseInt(times[0]), Integer.parseInt(times[1]));
			break;
		case R.id.rl_end_time:
			times = endTime.split(":");
			initTimePicker(true, Integer.parseInt(times[0]), Integer.parseInt(times[1]));
			break;
		default:
			break;
		}
	}
	/**
	 * 
	 * @param isWake 标记清醒还是睡眠状态
	 * @param hour	
	 * @param minute
	 */
	private void initTimePicker(final boolean isWake, int hour, int minute){
		new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
			
			@Override
			public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
				if(isWake){
					endTime = hourOfDay+":"+minute;
					tv_end_time.setText(hourOfDay+":"+minute);
					PreferenceHelper.putString("endTime", hourOfDay+":"+minute);
				}else{
					startTime = hourOfDay+":"+minute;
					tv_start_time.setText(hourOfDay+":"+minute);
					PreferenceHelper.putString("startTime", hourOfDay+":"+minute);
				}
			}
		}, 23, 0, true).show();
	}
}
